﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace intelliSys.NankaiUtilities.EventSynchronizer
{
    public class EventSourceProber
    {
        public static bool IsTypeDiscoverableInSourceProbing(Type type)
        {
            if (type.IsInterface || type.IsAbstract)
            {
                return false;
            }
            Type currentType = type;
            while (currentType.BaseType != null)
            {
                if (currentType.BaseType == typeof(NKUEventSource))
                {
                    return true;
                }
                currentType = currentType.BaseType;
            }
            return false;
        }
        public static IEnumerable<ILiveEventSource> Probe()
        {
            var eventAssembly = AppDomain.CurrentDomain.GetAssemblies().Where<Assembly>(assembly =>
            {
                return assembly.FullName.Contains("NKUEventClassLibrary");
            }).FirstOrDefault<Assembly>();
            var itemSourceTypes = eventAssembly.GetTypes().Where<Type>(type =>
            {
                return IsTypeDiscoverableInSourceProbing(type);
            });
            List<ILiveEventSource> iLiveEventSources = new List<ILiveEventSource>();
            foreach (Type type in itemSourceTypes)
            {
                iLiveEventSources.Add(Activator.CreateInstance(type) as ILiveEventSource);
            }
            return iLiveEventSources;
        }
    }
}
